package com.attilax.query;

import java.io.IOException;
import java.net.URLDecoder;
import java.util.List;
import java.util.Map;
//import java.util.Optional;

import javax.servlet.Servlet;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.lang3.reflect.MethodUtils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson.JSONObject;

//import aaaCfg.IocX4nodb;

import com.attilax.core;
import com.attilax.collection.list;
import com.attilax.db.DbServiceV4qb9;
import com.attilax.dsl.DslParser;
//import com.attilax.dsl.DslParser;
import com.attilax.exception.ExUtil;
import com.attilax.hre.UrlDslParser;
import com.attilax.hre.UrlDslParserV2;
import com.attilax.io.filex;
import com.attilax.ioc.Ioc4wash;
import com.attilax.ioc.IocFacV3_iocx_iocutil;
import com.attilax.ioc.IocUtilV2;
import com.attilax.ioc.IocXq214;
import com.attilax.json.AtiJson;
import com.attilax.lang.Global;
import com.attilax.net.requestImp;
import com.attilax.ref.refx;
import com.attilax.sql.Sqlbuilder;
import com.attilax.up.FileUploadService;
import com.attilax.web.ReqX;
import com.attilax.web.UrlX;
import com.attilax.web.responseImp;
import com.attilax.wechat.Order;
import com.attilax.wechat.WeChatPayUtil;
import com.attilax.wrmi.JsnaInvoker;
import com.attilax.wrmi.Wrmi;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.inject.Inject;

/** com.attilax.rest.Api
 * com.attilax.rest.DslAjaxJsbridge_HttpparamMode_servlet
 * com.attilax.order.RechargeOrderService jobus not use ,,can be game use ..
 * /CommonServlet?$method= com.attilax.up.FileUploadService.upload
 * 
 * /CommonServlet?$method= com.attilax.up.FileUploadService.process
 * 
 * @author Administrator
 * 
 *         / /jsnaServlet?$method=com.attilax.jsna.test.add&param1=2&param2=3
 *
 *         jeig he not support meth chain...deft use dyna new mode...
 *         v2 will add stati mode
 */
/**
 * for wash @WebxxServlet (name = "api_name", urlPatterns = "/api")
 * 
 * @author Administrator
 *
 */
//  com.attilax.query.jsondslQueryApi
public class jsondslQueryApi implements Servlet {

	public static void main(String[] args) {
		System.setProperty("prj", "com.attilax.rest.JavaNewCreatorFac");
		System.setProperty("agent_cfgfile", "cfg_game.properties");
		System.out.println("2333");

		responseImp resImp = new responseImp();
		requestImp ri = new requestImp();
		// ri.setParam("iocFac", "com.attilax.rest.JavaNewCreatorFac");
		// ri.setParam("c", "");
		ri.setParam("m", "com.attilax.rest.Class4test.m1");
		ri.setParam("p1_type", "s");
		ri.setParam("p1", "select * from agt");
		new jsondslQueryApi().service(ri, resImp);
		System.out.println("--f122");
		logger.error("--e44rr10");
		// org.apache.xmlbeans
		// org.apache.xmlbeans
	}

	@Override
	public void destroy() {
		// TODO Auto-generated method stub

	}

	@Override
	public ServletConfig getServletConfig() {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public String getServletInfo() {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public void init(ServletConfig paramServletConfig) throws ServletException {

		// UrlDslParserx = IocXq214.getBean(UrlDslParser.class);

	}

	public static ThreadLocal<ServletResponse> resp = new ThreadLocal<ServletResponse>();

	@Inject
	UrlDslParser UrlDslParserx;

	private static boolean isBaseDateType(Object s) {
		if (s.getClass() == Integer.class)
			return true;
		if (s.getClass() == String.class)
			return true;
		System.out.println();
		return false;
	}

	@Override
	public void service(ServletRequest req, ServletResponse response) {
		try {
			HttpServletResponse res = (HttpServletResponse) response;
			res.setHeader("Access-Control-Allow-Origin", "*");
			HttpServletRequest req2 = (HttpServletRequest) req;
			Global.req.set(req2);
			Object rzt;

			String jsondsl = req.getParameter("jsondsl");
			Map m_jsondsl = JSONObject.parseObject(jsondsl);
			Sqlbuilder sqlbld = Ioc4wash.getBean(Sqlbuilder.class);
			String sql = sqlbld.toQuerySql(m_jsondsl);
			DbServiceV4qb9 dbs = Ioc4wash.getBean(DbServiceV4qb9.class);
			rzt = dbs.executeQuery(sql);

			String retFmt = getRetFmt(req);

			if (retFmt != null && retFmt.trim().equals("json"))
				response.getWriter().println(AtiJson.toJson(rzt)); // �벻Ҫ�޸Ļ�ɾ��
			else if (retFmt != null && retFmt.trim().equals("none"))
				response.getWriter().println(rzt.toString()); // �벻Ҫ�޸Ļ�ɾ��
			else if ((retFmt == null || retFmt.length() == 0) && isBaseDateType(rzt))
				response.getWriter().println(rzt);
			else // def obj type
				response.getWriter().println(AtiJson.toJson(rzt));
		} catch (Exception e) {
			logger.error("--err", e);
			logger.error("--err2", AtiJson.toJson(e));
			filex.save_safe(core.getTrace(e), "c:\\0rechglog\\" + filex.getUUidName() + ".log");
			ExUtil.throwExV2(e);
		}

	}

	private String getRetFmt(ServletRequest req) {
		// if (req.getParameter("retFmt") == null ||
		// req.getParameter("retFmt").trim().equals("") )
		// return "json";
		// else
		return req.getParameter("retFmt");
	}

	private boolean isStaticMode(String createmode) {
		if (createmode == null)

			return false;
		if (createmode.trim().length() == 0)
			return false;
		if (createmode.trim().equals("static"))
			return true;
		// if(createmode.trim().equals("static"))
		// return this;
		// throw new RuntimeException("ille create mode");
		return false; // def

	}

	private String getClassStr(ServletRequest req) {

		String m;
		if (req.getParameter("class") != null)
			return req.getParameter("class").trim();
		// method is null
		try {
			return req.getParameter("c").trim();
		} catch (Exception e) {
			throw new RuntimeException(" m param is illege");
		}
	}

	private String getMeth(ServletRequest req) {

		if (req.getParameter("method") != null && req.getParameter("method").trim().toLowerCase().equals("q"))
			return "com.attilax.db.DbServiceV4qb9.executeQuery";
		if (req.getParameter("m") != null && req.getParameter("m").trim().toLowerCase().equals("q"))
			return "com.attilax.db.DbServiceV4qb9.executeQuery";

		if (req.getParameter("method") != null && req.getParameter("method").trim().toLowerCase().equals("u"))
			return "com.attilax.db.DbServiceV4qb9.executeUpdate";
		if (req.getParameter("m") != null && req.getParameter("m").trim().toLowerCase().equals("u"))
			return "com.attilax.db.DbServiceV4qb9.executeUpdate";
		String m;
		if (req.getParameter("method") != null)
			return req.getParameter("method").trim();
		// method is null
		try {
			return req.getParameter("m").trim();
		} catch (Exception e) {
			throw new RuntimeException(" m param is illege");
		}

	}

	private String get_iocFac(String parameter) {
		if (parameter == null || parameter.trim().equals(""))
			return "com.attilax.ioc.Ioc4wash";
		return parameter.trim();
	}

	private boolean isNewMode(String createmode) {

		if (createmode == null)

			return false;
		if (createmode.trim().length() == 0)
			return false;
		if (createmode.trim().equals("new"))
			return true;
		// if(createmode.trim().equals("static"))
		// return this;
		// throw new RuntimeException("ille create mode");
		return false; // def
	}

	private Object getP(String p, String ptype) {
		if (ptype.equals("s") || ptype.equals("str")) {
			return p;
		} else if (ptype.equals("opt") && p.equals("$empty")) {

			return (Optional.empty());
		} else if (ptype.equals("opt<map>")) {
			Map m = Maps.newConcurrentMap();
			String[] a = p.split(",");
			for (String kv : a) {
				String[] kv_item = kv.split(":");
				m.put(kv_item[0], kv_item[1]);
			}
			return (Optional.of(m));

		}
		throw new RuntimeException("getP.ex");
	}

	private String getPtype(ServletRequest req, String pname) {
		String ptype = req.getParameter(pname + "_type");
		if (ptype == null)
			ptype = "str";
		else if (ptype.length() == 0)
			ptype = "str";
		return ptype;
	}

	public static final Logger logger = LoggerFactory.getLogger(jsondslQueryApi.class);

}
